#include "CSoundPlayer.h"
#include "SimpleAudioEngine.h"

USING_NS_CC;
using namespace CocosDenshion;

CSoundPlayer::CSoundPlayer():
	__enemyExplosionId(0),
	__shipExplosionId(0),
	__bombExplosionId(0),
	__bombShotId(0),
	__standardId(0),
	__pSounds(NULL)
{
	__pSounds = CCDictionary::dictionaryWithContentsOfFile("sounds.plist");
	__pSounds->retain();
}

CSoundPlayer::~CSoundPlayer()
{
	__pSounds->release();
}

void
CSoundPlayer::playBackgroundMusic()
{
	playSound(__pSounds->objectForKey("backgroundMusic"));
}

void
CSoundPlayer::playEnemyExplosion()
{
	playSound(__pSounds->objectForKey("enemyExplosion"), &__enemyExplosionId);
}

void
CSoundPlayer::playShipExplosion()
{
	playSound(__pSounds->objectForKey("shipExplosion"), &__shipExplosionId);
}

void
CSoundPlayer::playBombExplosion()
{
	playSound(__pSounds->objectForKey("bombExplosion"), &__bombExplosionId);
}

void
CSoundPlayer::playBombShot()
{
	playSound(__pSounds->objectForKey("bombShot"), &__bombShotId);
}

void
CSoundPlayer::playStandardShot()
{
	playSound(__pSounds->objectForKey("standardShot"), &__standardId);
}

void
CSoundPlayer::end()
{
	SimpleAudioEngine::sharedEngine()->end();
}

/**
 * @param fileName This should be equal to the value returned by the objectForKey() method of CCMutableDictionary.
 * @param soundId This an in/out parameter.
 * 				  If set, a sound effect of id equal to soundId will be restarted.
 * 				  The new id will be returned through soundId.
 */
void
CSoundPlayer::playSound(cocos2d::CCObject* fileName, unsigned int* soundId)
{
	CCString* fileNameCCString = static_cast<CCString*>(fileName);
	const char* cfileName = fileNameCCString->getCString();
	if(!soundId)
	{
		SimpleAudioEngine::sharedEngine()->playBackgroundMusic(CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(cfileName), true);
	}
	else
	{
		SimpleAudioEngine::sharedEngine()->stopEffect(*soundId);
		*soundId = SimpleAudioEngine::sharedEngine()->playEffect(CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(cfileName));
	}
}

